﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class UnitComposeManager : MonoBehaviour
{
    public MyUnitCard originalCard;
    public MyUnitCard resultCard;

    public GameObject levelResultPreview;
    public UILabel previewLevel;
    public UILabel[] previewStatLabel;
    public UILabel[] previewPlusStatLabel;

    public GameObject levelupResultPopup;
    public MyUnitCard resultCardInPopup;
    public UILabel[] resultLevel;
    public UILabel[] resultStatLabel;
    public UILabel[] resultPlusStatLabel;
    public UILabel[] resultSkillInfo;

    public UIGrid materialCardListGrid;

    public List<MyUnitCard> materialCardList;

    public UILabel requiredMoney;
    public UILabel acquiredExp;
    public UILabel acquiredExpMax;
    public UILabel expectedLevel;

    public UISprite okButton;
    public UILabel warningText;

    public UILabel curMaterialCardCount;

    public static UnitInfo originalUnitInfo = null;
    public static List<UnitInfo> materialUnitInfo = null;

    public UISlider expSlider;

    public GameObject blankMaterialCardObject;

    public GameObject completeButton;

    int _expectedLevel = 0;
    // Use this for initialization
    void Start()
    {
        okButton.collider.enabled = false;
        int level = 0;

        if (!DeckCardSelectSceneManager.isMultySelect)
        {
            if (DeckCardSelectSceneManager.SelectCardInfos.Count > 0)
                originalUnitInfo = DeckCardSelectSceneManager.SelectCardInfos[0];
        }
        else
            materialUnitInfo = DeckCardSelectSceneManager.SelectCardInfos;

        if (originalUnitInfo != null)
        {
            level = originalUnitInfo.UnitLevel;
            if (originalUnitInfo.UnitDBID != 0)
            {
                originalCard.SetCardInfo(0, originalUnitInfo);
                originalCard.gameObject.SetActive(true);
            }
        }

        if (DeckCardSelectSceneManager.isMultySelect && materialUnitInfo.Count > 0)
        {
            int totalCombineCost = 0;
            int totalAcquireExp = 0;
            int expectedLevel = 0;
            //            okButton.spriteName = "button_decision";
            foreach (UnitInfo selectedUnitIfo in materialUnitInfo)
            {
                foreach (UnitInfo info in MyInfo.Instance.MyUnitsList)
                {
                    if (info.UnitDBID == selectedUnitIfo.UnitDBID)
                    {
                        if (info.UnitLevel > 1)
                            totalAcquireExp += CUnitExpDataManager.Instance.GetUnitCurrentLevelMaxExp(info.grade, 0) +
                                              (int)((CUnitExpDataManager.Instance.GetUnitCurrentLevelMaxExp(info.grade, info.UnitLevel - 1) + info.exp) * 0.75);
                        else
                            totalAcquireExp += CUnitExpDataManager.Instance.GetUnitCurrentLevelMaxExp(info.grade, 0) + (int)(info.exp * 0.75);

                        Debug.LogError(info.UnitLevel);
                        int combineCost = CUnitCombineCostDataManager.Instance.GetUnitCombineCostData(info.grade, info.UnitLevel);
                        Debug.LogError(combineCost);
                        totalCombineCost += combineCost;
                        break;
                    }
                }
            }

            foreach (UnitInfo info in MyInfo.Instance.MyUnitsList)
            {
                if (originalUnitInfo.UnitDBID == info.UnitDBID)
                {
                    int[] gradeExpList = CUnitExpDataManager.Instance.GetCurrentGradeExpsToArray(info.grade);
                    int currentTotalExp = info.exp + totalAcquireExp + gradeExpList[info.UnitLevel - 1];
                    expectedLevel = info.UnitLevel;
                    for (int i = info.UnitLevel; i < gradeExpList.Length; i++)
                    {
                        if (currentTotalExp < gradeExpList[i])
                        {
                            expectedLevel = i;
                            break;
                        }
                    }
                }
            }

            _expectedLevel = expectedLevel;

            int MaxExp = CUnitExpDataManager.Instance.GetUnitCurrentLevelMaxExp(originalUnitInfo.grade, expectedLevel);
            int expectedExp = totalAcquireExp + originalUnitInfo.exp;
            acquiredExp.text = expectedExp.ToString();
            acquiredExpMax.text = MaxExp.ToString();
            expSlider.value = (float)expectedExp / MaxExp;
            requiredMoney.text = totalCombineCost.ToString();
            this.expectedLevel.text = expectedLevel.ToString() + "LV";
            curMaterialCardCount.text = materialUnitInfo.Count.ToString();
            okButton.collider.enabled = true;
            blankMaterialCardObject.SetActive(false);


            CUnitData baseUnitData = CUnitDataManager.Instance.GetUnitData(originalUnitInfo.UnitClassID);
            CUnitAbilityItem plusUnitData = CUnitAbilityDataManager.Instance.GetUnitAbilityData(expectedLevel + "_" + baseUnitData.unit_class);
            CUnitAbilityItem plusUnitData_LV1 = CUnitAbilityDataManager.Instance.GetUnitAbilityData("1_" + baseUnitData.unit_class);
            resultCard.SetCardInfo(1, expectedLevel, baseUnitData, plusUnitData);

            previewLevel.text = expectedLevel.ToString();
            previewStatLabel[0].text = (baseUnitData.attack_base + plusUnitData_LV1.attack + plusUnitData.attack).ToString();
            previewStatLabel[1].text = (baseUnitData.defense_base + plusUnitData_LV1.defense + plusUnitData.defense).ToString();
            previewStatLabel[2].text = (baseUnitData.move_base + plusUnitData_LV1.move + plusUnitData.move).ToString();
            previewStatLabel[3].text = (baseUnitData.max_hp + plusUnitData_LV1.max_hp + plusUnitData.max_hp).ToString();
            previewPlusStatLabel[0].text = "(+" + plusUnitData.attack.ToString() + ")";
            previewPlusStatLabel[1].text = "(+" + plusUnitData.defense.ToString() + ")";
            previewPlusStatLabel[2].text = "(+" + plusUnitData.move.ToString() + ")";
            previewPlusStatLabel[3].text = "(+" + plusUnitData.max_hp.ToString() + ")";

            resultCard.gameObject.SetActive(true);
            levelResultPreview.SetActive(true);

            blankMaterialCardObject.SetActive(false);
            SetMaterialCardsInfo();

            if (MyInfo.Instance.Money >= totalCombineCost)
                completeButton.SetActive(true);
        }

    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnClickMainUnitSelect()
    {
        MyInfo.Instance.LastSeletedUnitSlot = 0;
        MyInfo.Instance.LastSelectedUnitDBID = 0;
        MyInfo.Instance.LastSelectedUnitID = 0;
        CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
        c.GoToUnitInvenScene();
    }

    void OnClickAddMaterialCard()
    {
        if (MyInfo.Instance.LastSelectedUnitID != 0)
        {
            MyInfo.Instance.LastSelectedUnitIDs.Clear();
            MyInfo.Instance.LastSelectedUnitDBIDs.Clear();
            CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
            c.GoToSelectUnitScene();
        }
        else
        {
            warningText.gameObject.SetActive(true);
        }
    }

    void OnClickSelectOriginalCard()
    {
        DeckCardSelectSceneManager.isEnhance = true;
        DeckCardSelectSceneManager.isMultySelect = false;
        DeckCardSelectSceneManager.SelectCardInfos.Clear();
        CSceneManager.manager.GoToSelectUnitScene();
    }

    void SetOriginalCardInfo(UnitInfo unitInfo)
    {
        originalCard.SetCardInfo(0, unitInfo);
    }

    void OnClickedMaterialCard()
    {
        DeckCardSelectSceneManager.isEnhance = true;
        DeckCardSelectSceneManager.isMultySelect = true;
        DeckCardSelectSceneManager.SelectCardInfos.Clear();
        DeckCardSelectSceneManager.OrizinCard = originalUnitInfo;
        CSceneManager.manager.GoToSelectUnitScene();
    }

    void SetMaterialCardsInfo()
    {
        int index = 0;
        foreach (UnitInfo unitInfo in materialUnitInfo)
        {
            MyUnitCard card = LTPrefabManager.InstantiateC(PrefabTypes.Card1, Vector3.zero, Quaternion.identity) as MyUnitCard;
            card.transform.parent = materialCardListGrid.transform;
            card.transform.localScale = new Vector3(0.45f, 0.45f, 1f);
            card.transform.localPosition = Vector3.zero;
            card.SetCardInfo(index++, unitInfo);

            materialCardList.Add(card);
        }

        materialCardListGrid.Reposition();
    }

    void OnClickedCompleteButton()
    {
        LoadingWindow.window.ShowShortLoading();
        List<int> materialUnitList = new List<int>();
        foreach (UnitInfo info in materialUnitInfo)
        {
            Debug.LogError(info.UnitDBID);
            materialUnitList.Add(info.UnitDBID);
        }

        prevUnitLevel = originalUnitInfo.UnitLevel;
        RestAPI.singleton.SendUnitComposeResult(RestCallback, originalUnitInfo.UnitDBID, materialUnitList);
    }

    int prevUnitLevel = 0;
    void RestCallback(Hashtable returnData)
    {
        LoadingWindow.window.HideLoading();

        switch ((RestAPIProtocol)returnData["protocol"])
        {
            case RestAPIProtocol.SENDUNITCOMPOSERESULT:
                CUnitData baseUnitData = CUnitDataManager.Instance.GetUnitData(originalUnitInfo.UnitClassID);
                CUnitAbilityItem plusUnitData = CUnitAbilityDataManager.Instance.GetUnitAbilityData(_expectedLevel + "_" + baseUnitData.unit_class);
                CUnitAbilityItem plusUnitData_LV1 = CUnitAbilityDataManager.Instance.GetUnitAbilityData("1_" + baseUnitData.unit_class);
                resultCardInPopup.SetCardInfo(1, _expectedLevel, baseUnitData, plusUnitData);

                resultLevel[0].text = prevUnitLevel.ToString();
                resultLevel[1].text = _expectedLevel.ToString();
                resultStatLabel[0].text = (baseUnitData.attack_base + plusUnitData_LV1.attack + plusUnitData.attack).ToString();
                resultStatLabel[1].text = (baseUnitData.defense_base + plusUnitData_LV1.defense + plusUnitData.defense).ToString();
                resultStatLabel[2].text = (baseUnitData.move_base + plusUnitData_LV1.move + plusUnitData.move).ToString();
                resultStatLabel[3].text = (baseUnitData.max_hp + plusUnitData_LV1.max_hp + plusUnitData.max_hp).ToString();
                resultPlusStatLabel[0].text = "(+" + plusUnitData.attack.ToString() + ")";
                resultPlusStatLabel[1].text = "(+" + plusUnitData.defense.ToString() + ")";
                resultPlusStatLabel[2].text = "(+" + plusUnitData.move.ToString() + ")";
                resultPlusStatLabel[3].text = "(+" + plusUnitData.max_hp.ToString() + ")";

                CSkillData skillData = CSkillDataManager.Instance.FindSkillData(baseUnitData.passive_skill);
                if (skillData != null)
                {
                    resultSkillInfo[0].text = CStringTableManager.Instance.GetItemByName(skillData.name_string);
                    resultSkillInfo[1].text = CStringTableManager.Instance.GetItemByName(skillData.desc_string);
                }
                else
                {
                    resultSkillInfo[0].gameObject.SetActive(false);
                    resultSkillInfo[1].gameObject.SetActive(false);
                }

                levelupResultPopup.SetActive(true);
                DeckCardSelectSceneManager.SelectCardInfos.Clear();
                break;
            case RestAPIProtocol.GETMYUNITLIST:
                break;
        }
    }

    void CompleteLevelup()
    {
        levelupResultPopup.SetActive(false);
        originalCard.gameObject.SetActive(false);
        resultCard.gameObject.SetActive(false);
        levelResultPreview.SetActive(false);
        materialUnitInfo.Clear();
        for (int i = 0; i < materialCardList.Count; i++)
        {
            materialCardList[i].transform.localPosition = new Vector3(10000f, 10000f, 0f);
            Destroy(materialCardList[i].gameObject);
        }
        materialCardList.Clear();
        blankMaterialCardObject.SetActive(true);
        requiredMoney.text = "0";
        acquiredExp.text = "0";
        acquiredExpMax.text = "0";
        expectedLevel.text = "0LV";
        expSlider.value = 0f;
        curMaterialCardCount.text = "0";
        expSlider.value = 0f;
        UnitInfo.AllUnitInfosUnCheck(MyInfo.Instance.MyUnitsList);
        LoadingWindow.window.ShowShortLoading();
        RestAPI.singleton.GetMyUnitList(RestCallback);
    }
}
